import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router'
import { useUserStore } from '../store/user'

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'home',
        component: () => import('../views/Home.vue')
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/Login.vue')
    },
    {
        path: '/register',
        name: 'register',
        component: () => import('../views/Register.vue')
    },
    {
        path: '/add-movie',
        name: 'add-movie',
        component: () => import('../views/AddMovie.vue'),
        meta: { requiresAuth: true }
    },
    {
        path: '/movie/:id',
        name: 'movie-detail',
        component: () => import('../views/MovieDetail.vue'),
        props: true
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach((to, _from, next) => {
    const userStore = useUserStore()

    if (to.meta.requiresAuth && !userStore.isLoggedIn) {
        next({ name: 'login' })
    } else {
        next()
    }
})

export default router